/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package bll;

import dal.QuanAoDAL;
import bean.NguoiDung;
import bean.ThongTinNguoiDung;
import java.sql.ResultSet;
import java.util.List;
import helper.Converter;
import helper.Supporter;

/**
 *
 * @author HoangNam
 */
public class UserBLL {

    private QuanAoDAL dal;
    private Converter conv;

    public UserBLL() {
        dal = new QuanAoDAL();
        conv = new Converter();
    }

    public NguoiDung login(String username, String pass) {
        NguoiDung user = getUserByUsername(username);
        if (user != null) {
            String str = Supporter.md5Encrypt(pass);
            if (user.getPassword().equals(Supporter.md5Encrypt(pass))) {
                ThongTinNguoiDung info = getUserInfoByID(user.getUserID());
                user.setThongTinNguoiDung(info);
                return user;
            }
        }
        return null;
    }

    public ThongTinNguoiDung getUserInfoByID(int id) {
        String sql = "select * from ThongTinNguoiDung where userid = ?";
        Object[] arr = {id};
        ResultSet rs = dal.executeQuery(sql, arr);
        ThongTinNguoiDung info = (ThongTinNguoiDung) conv.getObject(ThongTinNguoiDung.class, rs);
        return info;
    }

    private NguoiDung getUserByUsername(String username) {
        String cmd = "select * from NguoiDung where username = ?";
        Object[] arr = {username};
        ResultSet rs = dal.executeQuery(cmd, arr);
        NguoiDung user = (NguoiDung) conv.getObject(NguoiDung.class, rs);
        return user;
    }

    private List<NguoiDung> getAllUser() {
        String cmd = "select * from NguoiDung";
        ResultSet rs = dal.executeQuery(cmd, null);
        List<NguoiDung> list = conv.getObjectList(NguoiDung.class, rs);
        return list;
    }

    public static void main(String[] args) {
        UserBLL bll = new UserBLL();
        NguoiDung user = bll.login("admin", "123456");
        System.out.println(user);
//        List<NguoiDung> list = bll.getAllUser();
//        for (Master item : list) {
//            System.out.println(item);
//        }
    }
}
